package com.example.ms;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;


public class FunASRWebSocketClient extends WebSocketClient {

    private final TextArea outContext;

    private final Button close;

    private final Button connect;

    private TextArea inContext;

    public FunASRWebSocketClient(URI serverUri, TextArea context,TextArea inContext,Button cn, Button co) {
        super(serverUri);
        this.outContext = context;
        this.close = co;
        this.connect = cn;
        this.inContext = inContext;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        outContext.appendText("\n连接成功 : " + getURI()+"\n");
        // 发送初始化数据
        FunASREntity funASREntity = new FunASREntity("2pass", "wav_name", true, "pcm", new long[]{5,10,5}, null, true, "16000");
        send(JSONUtil.toJsonStr(funASREntity));
        close.setDisable(false);
    }

    @Override
    public void onMessage(String s) {
        JSONObject respJson = JSONUtil.parseObj(s);
        String text = respJson.getStr("text");
        // 识别出一句话
        if ("2pass-offline".equals(respJson.get("mode")) && text.length() >= 2) {
            String replaceText = text.replaceAll("。", "。\n");
            outContext.appendText("\n" + replaceText);
            inContext.setText("");
        }else {
            inContext.appendText(text);
        }
        System.out.println("收到消息 :" + respJson);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        outContext.appendText("\n连接关闭 code: " + i);
        connect.setDisable(false);
        close.setDisable(true);
    }

    @Override
    public void onError(Exception e) {
        outContext.appendText("\n连接错误 : " + e.getMessage());
        connect.setDisable(false);
        e.printStackTrace();
    }
}
